package org.csu.myProject.web.servlet;

import org.csu.myProject.domain.User;
import org.csu.myProject.service.UserService;
import org.csu.myProject.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class LoginServlet extends HttpServlet {

    private static final String LOGIN_FORM = "/WEB-INF/jsp/login.jsp";
    private static final String MAIN_JSP = "/WEB-INF/jsp/main.jsp";
    //private static final String INFO_JSP = "/WEB-INF/jsp/info.jsp";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        UserService userService = new UserServiceImpl();

        User loginUser = userService.login(username, password);

        if(loginUser == null)
        {
            //登录失败
            req.setAttribute("msg", "用户名或密码错误");
            req.getRequestDispatcher(LOGIN_FORM).forward(req,resp);
        }else{
            //登录成功
            HttpSession session = req.getSession();
            session.setAttribute("loginUser", loginUser);
            if(loginUser.isAdmin()){
                //管理员
                List<User> userList = userService.getUserList();
                session.setAttribute("userList", userList);
                req.getRequestDispatcher(MAIN_JSP).forward(req,resp);
            }else{
                //普通用户
                User userInfo = userService.getUserInfo(loginUser.getId());
                session.setAttribute("userInfo", userInfo);
                req.getRequestDispatcher("/info").forward(req,resp);
            }
        }
    }
}
